 var mapPosition, mapOptions, map;
var weatherLayer, cloudLayer;
var sv = new google.maps.StreetViewService();
var panorama, panoramaOptions;
var getPoints;                                                             //Variable and Arrays(Dont set them in methods)
var getTextBoxValue;
var getTextBoxValue2;
var lookPosition;
var lookUpAndDownPosition;
var zoomPosition, zoomPositionMap;
var patternsArray = [];
var storeFun = [];

//Arrays for panning,looking and zooming(created to fingd patterns)
var panLeft = ["Python left", "pon left", "uh left", "pan left", "han left", "palm left", "on left", "haha left", "haha i left", "ha left", "ha i left", "hi im left", "haha next", "hi left", "pine left", "on next", "han left", "Python last", "pa on left", "time left", "pine less", "Pub left",
"I left", "hi I left", "a left"];
var panRight = ["Python right", "pine right", "haha really", "uh really", " hah really", "haha right", "ah right", "pon right", "han Roy", "pon Royce", "pine Royce", "pan right", "Python Royce", "palm right", "Pomeroy"];
var lookUp = ["look up", "local opp", "milk open", "milk help", "milk hope", "milk pump", "milk there", "look OTP", "look both", "local open", "Lok opp", "local OTP", "look old", "Lok open"];
var lookDown = ["look down", "milk down"];
var zoomIn = ["zoom in"];
var zoomOut = ["zoom out", "zoom else", "zoom lol", "zoom FX","zoom"];
var zoomInMap = ["zoom in map", "zoom in math", "zoom in my", "zoom in my eye"];
var zoomOutMap = ["zoom out map", "zoom else map", "zoom ELT map", "zoom and mop", "zoom and a map", "zoom map", "zoom and my", "zoom bye"];
var markersArray =[];

var findLookUp = "lo";
var lngpoint, latpoint, coOrd;
var updateCoordinates;

//Dictionaries for cities,stores,mapTypes and co-ordinate calculations designated for quicker retrievals
var cities = {
               "London": new google.maps.LatLng(51.50795, -0.12893), "london": new google.maps.LatLng(51.50795, -0.12893), "Dublin": new google.maps.LatLng(53.34876, -6.25972), 
                "open": new google.maps.LatLng(53.34876, -6.25972), "Tobin": new google.maps.LatLng(53.34876, -6.25972),
                "Paris": new google.maps.LatLng(48.85793, 2.29542), "New York": new google.maps.LatLng(40.75964, -73.98441),
                "Sydney": new google.maps.LatLng(-33.85923, 151.21351),"Madrid": new google.maps.LatLng(40.45214 ,- 3.69089),
                "Amsterdam": new google.maps.LatLng(52.37010,4.89627),  "Munich": new google.maps.LatLng(48.14356,11.57804),
                "Rome": new google.maps.LatLng(41.90020,12.45650)
            };
            var storesAndResteraunts = 
            { 
                "restaurant": 'restaurant', "restaurants": 'restaurant', "stores": 'store',
                "stars": 'store', "star": 'store', "churches": 'church', "cafes": 'cafe', "Cafe": 'cafe'
                ,"cafe" :'cafe',"charges":'church'
            };

            var mapModes = 
            {
                "something like": google.maps.MapTypeId.SATELLITE, "my": google.maps.MapTypeId.ROADMAP, "softly": google.maps.MapTypeId.SATELLITE, "South elite": google.maps.MapTypeId.SATELLITE, "South Philly": google.maps.MapTypeId.SATELLITE, "Sausalito": google.maps.MapTypeId.SATELLITE, "soccer": google.maps.MapTypeId.SATELLITE, "map": google.maps.MapTypeId.ROADMAP, "satellite": google.maps.MapTypeId.SATELLITE, "Southlake": google.maps.MapTypeId.SATELLITE,
                "subtly": google.maps.MapTypeId.SATELLITE, "cycle is": google.maps.MapTypeId.SATELLITE, "psychedelic": google.maps.MapTypeId.SATELLITE,
                "suck a lease": google.maps.MapTypeId.SATELLITE, "subtly to": google.maps.MapTypeId.SATELLITE, "sucks at least": google.maps.MapTypeId.SATELLITE,
                "terrain": google.maps.MapTypeId.TERRAIN, "arrange": google.maps.MapTypeId.TERRAIN, "to rain": google.maps.MapTypeId.TERRAIN, "Holly Bridget": google.maps.MapTypeId.HYBRID, "holy bread": google.maps.MapTypeId.HYBRID,
                "holy bridge": google.maps.MapTypeId.HYBRID, "Holly bridge": google.maps.MapTypeId.HYBRID, "Clippers": google.maps.MapTypeId.HYBRID

             };
             var coOrdinateCalculations = [
                                            {
                                            "AlterLat":0.000105,
                                            "AlterLng":0.000163
                                        },
                                        {
                                            "AlterLat": 0.000135,
                                            "AlterLng": 0.0001
                                        }

                                        ];



 //###############Commands#####################
   // Pan Left,Pan Right
  // Turn Left,Turn Right
  // Look Up, Look Down
  //Zoom In,Zoom Out,Zoom In Map,Zoom Out Map
  // Go Forward,Go Back
  //Turn Around  
  //Go to (city)
  //Show resteraunts,stores,churches
 //Change map modes
 //Show weather
 //Save and load locations
 // Show commands


   


//##########################################
             //When Speech is Recieved
//##########################################
  function append() 
{
    $('#check').empty();
    $('#warningText').empty();
    $('#successText').empty();
    


    getTextBoxValue = document.getElementById("input").value;               //get the value in the hidden text box once the speech is finished  
    getTextBoxValue2 = document.getElementById("input").value.toLowerCase();

    coOrd = panorama.getPosition();
    lngpoint = coOrd.lng();                                                 // gets the position of the street view 
    latpoint = coOrd.lat();
    getPoints = map.getCenter();

    lookUpAndDownPosition = panorama.getPov().pitch;
    lookPosition = panorama.getPov().heading;
    zoomPosition = panorama.getPov().zoom;
    zoomPositionMap = map.getZoom();

    findGoTo1InTextBox = getTextBoxValue.indexOf("go to");                 // look for specific values in the text box when you speak,this retrieves a numeric value greater than -1 if a pattern is found
    findLookUpInTextBox = getTextBoxValue2.indexOf(findLookUp);
    findMilkInTextBox = getTextBoxValue2.indexOf("milk");
    findCallToInTextBox = getTextBoxValue2.indexOf("call to");
    findGoTo2InTextBox = getTextBoxValue2.indexOf("goto");
    findZoomInTextBox = getTextBoxValue2.indexOf("zoom");
    findFallingInTextBox = getTextBoxValue2.indexOf("falling");
    findFindInTextBox = getTextBoxValue2.indexOf("find");
    findModInTextBox = getTextBoxValue2.indexOf("mod");
    findForwardInTextBox = getTextBoxValue2.indexOf("forward");
    findFoInTextBox = getTextBoxValue2.indexOf("fo");
    findBackInTextBox = getTextBoxValue2.indexOf("ack");
    findBack2InTextBox = getTextBoxValue2.indexOf("f***");
    findTurnInTextBox = getTextBoxValue2.indexOf("turn");

    findLocationInTextBox = getTextBoxValue2.indexOf("location");
    findSawAndInTextBox = getTextBoxValue2.indexOf("saw and");
    findPhoneAndInTextBox = getTextBoxValue2.indexOf("phone and");
    findShowInTextBox = getTextBoxValue2.indexOf("show");
    findWeatherInTextBox = getTextBoxValue2.indexOf("weather");
    findShareInTextBox = getTextBoxValue2.indexOf("share");
    findSendInTextBox = getTextBoxValue2.indexOf("send");



    lookPostion = lookPosition.toFixed(0); //0 decimal places
    if (lookPosition < 0) 
    {
        lookPosition = lookPosition + 360;
    }
    patternsArray = [];
    
     patternsArray.push(findLocationInTextBox);
     patternsArray.push(findForwardInTextBox);
     patternsArray.push(findFoInTextBox);
     patternsArray.push(findBackInTextBox);
     patternsArray.push(findBack2InTextBox);
     patternsArray.push(findTurnInTextBox);
     patternsArray.push(findModInTextBox);                //push the patterns you are looking for into the array
     patternsArray.push(findFallingInTextBox);
     patternsArray.push(findFindInTextBox);
     patternsArray.push(findSawAndInTextBox);
     patternsArray.push(findPhoneAndInTextBox);
     patternsArray.push(findWeatherInTextBox);
     patternsArray.push(findShowInTextBox);
     patternsArray.push(findZoomInTextBox);
     patternsArray.push(findGoTo1InTextBox);
     patternsArray.push(findGoTo2InTextBox);
     patternsArray.push(findCallToInTextBox);
     patternsArray.push(findLookUpInTextBox);
     patternsArray.push(findMilkInTextBox);
     patternsArray.push(contains(getTextBoxValue, panLeft));
     patternsArray.push(contains(getTextBoxValue, panRight));
     patternsArray.push(findShareInTextBox);
     patternsArray.push(findSendInTextBox);

     //store functions that you will retrieve
     storeFun = [saveAndLoadLocation, goBackOrForward, goBackOrForward, goBackOrForward, goBackOrForward, turnLeftRightAround, changeMapType, findStores, findStores, 
                 findStores, findStores, showWeather,showWeather,ZoomInOut, goToCity, goToCity, goToCity,LookUpAndDown,LookUpAndDown,lookLeft,lookRight,shareMap,sendMap];


     //search through the patterns array,if one position is not equal to -1 then find the corresponding function to match
    for(var i = 0; i < patternsArray.length;i++)
    {
        document.getElementById("textBox").value += patternsArray[i] + " ";
        if (patternsArray[i] != -1) {
            var fun = storeFun[i];
            fun();
            break;
        }
        else {
            if (i + 1 == patternsArray.length)          //if we have reached the end of the array then the value does not match anything in the array
            {
                $("#check").append("<strong>Error: The command you entered was not recognised</strong>");
                $("#Error").show().delay(5000).fadeOut();
                document.getElementById("textBox").value += document.getElementById("input").value + " error"; 
            }
        }
        
          
      }

//#############################
 //Display Div To share Map
//#############################
    function shareMap() 
    {
        $('#shareMap').show('slow');//bring up the send email form

        

    }
    function sendMap() //dummy function,executed in the HomePage.aspx
    {


    }
//###################################################
//            SAVING AND LOADING LOCATIONS
//###################################################
function saveAndLoadLocation()
{
//save to co-ordinates to local storage or load them from local storage depending on the command issued
    if (getTextBoxValue.substring(0, 4) == "load")
     {

        updateCoordinates = new google.maps.LatLng(localStorage.latitude, localStorage.longtitude);
        ModifyLocation(updateCoordinates, 90, 10);
       
        $("#successText").append("<strong>Location Successfully Loaded</strong>");
        $("#Success").show();
        $("#Success").show().delay(5000).fadeOut();

    }
    else if (getTextBoxValue.substring(0, 4) == "save") 
    {
        localStorage.latitude = latpoint;
        localStorage.longtitude = lngpoint;
        accessDialog("You have successfully saved your location.To retrieve your saved location say Load Location !!", "Successful Notification");

    }

}
//################################################
       //GO FORWARD OR BACKWARDS
//################################################
function goBackOrForward()
{


    //Going Forward
    if (findForwardInTextBox != -1 || findFoInTextBox != -1) 
    {

        goingForward();
    }
    //Going Back
    else 
    {
        goingBack();

    }
    document.getElementById("textBox").value += document.getElementById("input").value; 
    sv.getPanoramaByLocation(updateCoordinates, 50, processSVData);

}
//#########################
//TURN LEFT,RIGHT OR AROUND
//#########################
function turnLeftRightAround()
{
var findLeft = getTextBoxValue2.indexOf("left");
var findRight = getTextBoxValue2.indexOf("right");
var findAround = getTextBoxValue2.indexOf("around");
//turn left
if (findLeft != -1) {

turnLeft();//co-ordinates updated here
sv.getPanoramaByLocation(updateCoordinates, 50, processSVData);//find the nearest panorama based on the new co-ordinates
lookPosition = lookPosition - 90;

if (lookPosition < 0) {

lookPosition = lookPosition + 360;
}

ModifyHeadingOrPitch(lookPosition, lookUpAndDownPosition, zoomPosition);
}
//turn right
else if (findRight != -1) {
turnRight();
sv.getPanoramaByLocation(updateCoordinates, 50, processSVData);
lookPosition = lookPosition + 90;

if (lookPosition > 360) {

lookPosition = lookPosition - 360;
}

ModifyHeadingOrPitch(lookPosition, lookUpAndDownPosition, zoomPosition);
}
else {

lookPosition += 180;
if (lookPosition > 360) {
lookPosition -= 360;

}

ModifyHeadingOrPitch(lookPosition, lookUpAndDownPosition, zoomPosition);
}


}

//###########################################
//CHANGE MAP TYPE
//###########################################
function changeMapType()
{
    document.getElementById("textBox").value += document.getElementById("input").value; 
var findMapType = getTextBoxValue.substring(0, findModInTextBox - 1);


//retrieve map type from the dictionary
var getMapType = mapModes[findMapType];

if (getMapType === undefined) {

$("#check").append("<strong>Error:You have declared an incorrect Map Type </strong>");
$("#Error").show();
$("#Error").show().delay(5000).fadeOut();
}
else 
{
modifyMapType(getMapType);
}
}

//###########################################
//    FIND STORES
//###########################################
function findStores() {

var findPlaceTypes, getStore;
if (findFallingInTextBox != -1) 
{
findPlaceTypes = getTextBoxValue.substring(8);
}
else 
{
findPlaceTypes = getTextBoxValue.substring(5);
}


getStore = storesAndResteraunts[findPlaceTypes];

findPlaces(getStore);

}

//############################################################
//Display Weather or Show Commands
//############################################################
function showWeather()
{
    if (getTextBoxValue.substring(0, 4) == "show") 
{
    if (getTextBoxValue2.indexOf("commands") != -1 ||
       getTextBoxValue2.indexOf("instructions") != -1) {
        $(".fancybox").fancybox().trigger('click');

    }
    else if (getTextBoxValue2.indexOf("weather") != -1) {
        weatherLayer = new google.maps.weather.WeatherLayer({
            temperatureUnits: google.maps.weather.TemperatureUnit.CELSIUS  //create weather object
        });
        weatherLayer.setMap(map);

        cloudLayer = new google.maps.weather.CloudLayer();
        cloudLayer.setMap(map);
    }
    else 
    {
        $("#check").append("<strong>Error:The command was not identified properly. </strong>");
        $("#Error").show();
        $("#Error").show().delay(5000).fadeOut();
    }
}

else if (getTextBoxValue.substring(0, 6) == "remove") 
{
weatherLayer.setMap(null);
cloudLayer.setMap(null);
        

}

}

//############################################################
//ZOOM IN OR OUT STREET VIEW
//############################################################

function ZoomInOut() {

    if (contains(getTextBoxValue, zoomIn) != -1) 
{
zoomPosition += 1;
if (zoomPosition > 3) 
{
$("#warningText").append("<strong>Warning:You cannot Zoom any further</strong>");
$("#Warning").show();
$("#Warning").show().delay(5000).fadeOut();
zoomPosition = 3;

}
else {
ModifyHeadingOrPitch(lookPosition, lookUpAndDownPosition, zoomPosition);
}
}
else if (contains(getTextBoxValue, zoomOut) != -1) {
zoomPosition -= 1;
if (zoomPosition < 0) {
$("#warningText").append("<strong>Warning:You cannot Zoom any further</strong>");
$("#Warning").show();
$("#Warning").show().delay(5000).fadeOut();
zoomPosition = 0;

}
else {
ModifyHeadingOrPitch(lookPosition, lookUpAndDownPosition, zoomPosition);
}
}
//############################################################
//ZOOM IN OR OUT ROADMAP
//############################################################

else if (contains(getTextBoxValue, zoomInMap) != -1) {

zoomPositionMap += 2;
if (zoomPositionMap > 22) {
$("#warningText").append("<strong>Warning:You cannot Zoom any further</strong>");
$("#Warning").show();
$("#Warning").show().delay(5000).fadeOut();
zoomPositionMap = 22;

}
else {
ZoomInOutMap(zoomPositionMap);
}

}
else if (contains(getTextBoxValue, zoomOutMap) != -1) {

zoomPositionMap -= 2;
if (zoomPositionMap < 0) {
$("#warningText").append("<strong>Warning:You cannot Zoom any further</strong>");
$("#Warning").show();
$("#Warning").show().delay(5000).fadeOut();
zoomPositionMap = 0;

}
else {
ZoomInOutMap(zoomPositionMap);
}

}
else {
document.getElementById("textBox").value += document.getElementById("input").value;
}

}

//############################################################
//GO TO A PARTICULAR CITY
//############################################################
function goToCity()
{

    var getCityFromTextBox;
//based on patterns that are retrieved find the city name based on a substring in the textbox
if ((findGoTo1InTextBox != -1)) 
{
getCityFromTextBox = getTextBoxValue.substring(6);
}
else if (findCallToInTextBox != -1) {
getCityFromTextBox = getTextBoxValue.substring(8);
}
else {
getCityFromTextBox = getTextBoxValue.substring(5);
}

updateCoordinates = cities[getCityFromTextBox];
//if you are already in the city that you have spoken
if (latpoint.toFixed(3) == updateCoordinates.lat().toFixed(3) && lngpoint.toFixed(3) == updateCoordinates.lng().toFixed(3))
 {

$("#warningText").append("<strong>Warning:You are already in this city</strong>");
$("#Warning").show();
$("#Warning").show().delay(5000).fadeOut();
}
else {
ModifyLocation(updateCoordinates, 90, 10);
}


}

//#################################################################
//LOOKING UP AND DOWN ON THE MAP
//##################################################################

function LookUpAndDown()
{
//LOOKING UP
if (contains(getTextBoxValue, lookUp) != -1) {
lookUpAndDownPosition += 20;
if (lookUpAndDownPosition > 90) 
{
$("#warningText").append("<strong>Warning:You cannot look up any further</strong>");
$("#Warning").show();
$("#Warning").show().delay(5000).fadeOut();
}
else {


ModifyHeadingOrPitch(lookPosition, lookUpAndDownPosition, zoomPosition);
}
}


//LOOKING DOWN
else if (contains(getTextBoxValue, lookDown) != -1) 
{
lookUpAndDownPosition -= 20;
if (lookUpAndDownPosition < -90) {
$("#warningText").append("<strong>Warning:You cannot look down any further</strong>");
$("#Warning").show();
$("#Warning").show().delay(5000).fadeOut();

}
else {

ModifyHeadingOrPitch(lookPosition, lookUpAndDownPosition, zoomPosition);
}

}
else {
    $("#warningText").append("<strong>Warning:Command Not Recognised</strong>");
    $("#Warning").show();
    $("#Warning").show().delay(5000).fadeOut();

}


}

//###########################################################
//PAN LEFT OR RIGHT
//###########################################################
function lookLeft() //if the user wishes to look left without going anywhere
{
lookPosition = lookPosition - 60;

if (lookPosition < 0) {

lookPosition = lookPosition + 360;                //position should only be from 0 - 360
}

ModifyHeadingOrPitch(lookPosition, lookUpAndDownPosition, zoomPosition);     //reset the map




}

function lookRight()
{

lookPosition = lookPosition + 60;

if (lookPosition > 360) {

lookPosition = lookPosition - 360;
}

ModifyHeadingOrPitch(lookPosition, lookUpAndDownPosition, zoomPosition);


}


}



//############################################################
//           INIATILIZING MAP AND STREET VIEW
//#############################################################
var placesList;

function initialize() 
{

    $("#tooltip").tooltip
    ({
        show: {
            effect: "slideDown",                  //tooltip if the user does notknow all the commands
            delay: 250
        }
    });
    
    if (localStorage.visitedSite == undefined) 
    {

        $(".fancybox1").fancybox().trigger('click');
        localStorage.visitedSite = 1;
    }


    
    
    $("#dialog").dialog({ autoOpen: false });  //works when loading
    //$('#tool').hide();
    //$('#results').hide();

    $('#hideEmailConfirmation').is(":visible")
    {
        $('#MailSent').show().delay(5000).fadeOut();

    }
   

    if (localStorage.latPageReload == undefined && localStorage.lngPageReload == undefined) 
    {
        localStorage.latPageReload = 53.34876;
        localStorage.lngPageReload = -6.25972;
        localStorage.pitchPageRelod = 10;
        localStorage.headingPageRelod = 20;
    }

    
    mapPosition = new google.maps.LatLng(localStorage.latPageReload, localStorage.lngPageReload);
    mapOptions =
            {
                center: mapPosition,                             //object literals which stores the original map settings
                zoom: 7,
                mapTypeId: 'roadmap',  
                streetViewControl: true

            };
    map = new google.maps.Map(
            document.getElementById('map_canvas'), mapOptions);

    map.setTilt(45);

    
    //#################################################
          // Street View which is linked to map
    //##################################################

    panoramaOptions =
            {
                position: mapPosition,
                pov:
                {
                    heading: parseFloat(localStorage.headingPageRelod),
                    pitch: parseFloat(localStorage.pitchPageRelod),
                    zoom: 1
                }
            };

    panorama = new google.maps.StreetViewPanorama(document.getElementById('pano'), panoramaOptions);
    map.setStreetView(panorama);

   

   google.maps.event.addListener(panorama, 'position_changed', function() 
   {
            var positionCell = document.getElementById('position');
            positionCell.firstChild.nodeValue = panorama.getPosition();
   });
 
}










